﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using MediaFire;

namespace GetLink
{
    public partial class FormMain : Form
    {

        private FilesFolder _filesFolder;

        public FormMain()
        {
            InitializeComponent();
            _filesFolder = new FilesFolder();
            _filesFolder.PropertyChanged += _filesFolder_PropertyChanged;
        }

        void _filesFolder_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "Foldername":
                    lblFolderName.Text = _filesFolder.Foldername;
                    break;
                case "FilesCount":
                    lblFileCount.Text = _filesFolder.FilesCount;
                    break;
                case "FilesDownload":
                    var list = _filesFolder.FilesDownload;
                    LoadFilesDownload(list);
                    ReadnWrite.Write(list);
                    if (!string.IsNullOrEmpty(_filesFolder.Foldername))
                        ReadnWrite.Write(list, _filesFolder.Foldername + ".txt");
                    break;
                case "Percent":
                    _progressBar.Value = _filesFolder.Percent;
                    break;
                case "Error":
                    Utilites.ShowMessageError(_filesFolder.Error);
                    break;
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            lblFolderName.Text = string.Empty;
            lblFileCount.Text = string.Empty;
            _filesFolder.FilesDownload = ReadnWrite.Read();
            LoadFilesDownload();
        }

        private void btnGetFileInFolder_Click(object sender, EventArgs e)
        {
            _filesFolder.GetFilesFolder(txtLinkFolder.Text);
            _progressBar.Value = 1;
        }

        private void LoadFilesDownload(IEnumerable<FileDownload> list = null)
        {
            if (list == null)
                if (_filesFolder.FilesDownload == null) return;
                else
                    list = _filesFolder.FilesDownload;
            _filesFolderListView.Items.Clear();
            foreach (var fileDownload in list)
            {
                var item = new ListViewItem(fileDownload.Filename);
                item.SubItems.Add(fileDownload.Link);
                item.SubItems.Add(fileDownload.StrSize);
                _filesFolderListView.Items.Add(item);
            }
        }

      

        private void GetnSend2IDM(ListViewItem item)
        {
            var file = new FileDownload();
            file.GetLinkDownload(item.SubItems[1].Text);
            file.PropertyChanged += (sender1, e1) =>
                                        {
                                            switch (e1.PropertyName)
                                            {
                                                case "LinkDownload":
                                                    file.LinkDownload.SendToIDM();
                                                    item.SubItems[3].Text = "Send IDM";
                                                    break;
                                                case "Error":
                                                    Utilites.ShowMessageError(file.Error);
                                                    break;
                                                case "Percent":
                                                    _progressBar.Value = file.Percent;
                                                    break;
                                            }
                                        };
        }

        private void getAndSendToIDMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var item in _filesFolderListView.SelectedItems.Cast<ListViewItem>().Where(item => item.SubItems.Count <= 3))
            {
                GetnSend2IDM(item);
                item.SubItems.Add("Sending...");
            }
        }

        private void removeStatusToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var item in _filesFolderListView.SelectedItems.Cast<ListViewItem>().Where(item => item.SubItems.Count > 3))
            {
                if (item.SubItems.Count < 4) return;
                item.SubItems.RemoveAt(3);

            }

        }

        private void removeThisToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var item in _filesFolderListView.SelectedItems.Cast<ListViewItem>())
            {
                _filesFolderListView.Items.Remove(item);
            }
        }

        private void txtLinkFolder_DoubleClick(object sender, EventArgs e)
        {
            if (openFile.ShowDialog() != DialogResult.OK) return;
            var filename = Path.GetFileName(openFile.FileName);

            if (filename != null)
            {
                lblFolderName.Text = filename.Substring(0, filename.LastIndexOf('.'));
                txtLinkFolder.Text = filename;
            }


            var list = ReadnWrite.Read(openFile.FileName);
            if (list == null)
            {
                _filesFolderListView.Items.Clear();
                lblFolderName.Text = "File not Format of ";
                lblFileCount.Text = "0";
                return;
            }

            _filesFolder.FilesDownload = list;
            _filesFolder.Foldername = null;

            lblFileCount.Text = _filesFolder.FilesDownload.Count.ToString(CultureInfo.InvariantCulture);
        }

        private void clearListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtLinkFolder.Text = string.Empty;
            lblFolderName.Text = string.Empty;
            lblFileCount.Text = string.Empty;
            _filesFolder.FilesDownload.Clear();
            _filesFolderListView.Items.Clear();
        }

        private void pasteFromClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dataObject = Clipboard.GetDataObject();
            if (dataObject == null || !dataObject.GetDataPresent(DataFormats.Text)) return;

            var clipBoard = Clipboard.GetText().ToString(CultureInfo.InvariantCulture);
            var links = clipBoard.Split(new[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            //_filesFolderListView.Items.Clear();

            lblFolderName.Text = "Past from clipboard";
            lblFileCount.Text = links.Length.ToString(CultureInfo.InvariantCulture);
            foreach (var link in links.Where(l => l.Contains("http://www.mediafire.com/")))
            {
                var url = link.FindLinkMediafire();

                var item = new ListViewItem("Past from clipboard");
                item.SubItems.Add(url);
                item.SubItems.Add(string.Empty);
                _filesFolderListView.Items.Add(item);
            }
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var item in _filesFolderListView.Items.Cast<ListViewItem>())
                item.Selected = true;
        }

        private void openFileBatchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtLinkFolder_DoubleClick(sender, e);
        }

        private void defaultBrowserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_filesFolderListView.SelectedItems.Count < 1) return;

            foreach (var item in _filesFolderListView.SelectedItems.Cast<ListViewItem>())
            {
                const string status = "Browser";
                Process.Start(item.SubItems[1].Text);
                if (item.SubItems.Count < 4)
                {
                    item.SubItems.Add(status);
                }
                else
                {
                    item.SubItems[3].Text = status;
                }
            }
        }

        private void chromeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (_filesFolderListView.SelectedItems.Count < 1) return;

                foreach (var item in _filesFolderListView.SelectedItems.Cast<ListViewItem>())
                {
                    const string status = "Send to Chrome";
                    Process.Start(@"C:\Users\MinhVu\AppData\Local\Google\Chrome\Application\chrome.exe",
                                  item.SubItems[1].Text);
                    if (item.SubItems.Count < 4)
                    {
                        item.SubItems.Add(status);
                    }
                    else
                    {
                        item.SubItems[3].Text = status;
                    }
                }
            }
            catch (Exception exception)
            {
                Utilites.ShowMessageError(exception.Message);
            }


        }

        private void filefoxToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (_filesFolderListView.SelectedItems.Count < 1) return;

                foreach (var item in _filesFolderListView.SelectedItems.Cast<ListViewItem>())
                {
                    const string status = "Send to FireFox";
                    Process.Start(@"E:\Program Files\Mozilla Firefox\firefox.exe", item.SubItems[1].Text);
                    if (item.SubItems.Count < 4)
                    {
                        item.SubItems.Add(status);
                    }
                    else
                    {
                        item.SubItems[3].Text = status;
                    }
                }
            }
            catch (Exception exception)
            {
                Utilites.ShowMessageError(exception.Message);
            }

        }

        private void iEToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (_filesFolderListView.SelectedItems.Count < 1) return;
                foreach (var item in _filesFolderListView.SelectedItems.Cast<ListViewItem>())
                {
                    const string status = "Send to IE";
                    Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", item.SubItems[1].Text);
                    if (item.SubItems.Count < 4)
                    {
                        item.SubItems.Add(status);
                    }
                    else
                    {
                        item.SubItems[3].Text = status;
                    }
                }
            }
            catch (Exception exception)
            {
                Utilites.ShowMessageError(exception.Message);
            }


        }

        private void passwordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frm = new FormPassword();
            if (frm.ShowDialog() == DialogResult.Cancel) return;

            foreach (var item in _filesFolderListView.SelectedItems.Cast<ListViewItem>())
            {
                const string ps = "&pass=";
                var link = item.SubItems[1].Text;
                if (link.Contains(ps))
                {
                    item.SubItems[1].Text = link.Substring(0, link.LastIndexOf("&", StringComparison.Ordinal));

                    if (!string.IsNullOrEmpty(frm.Password))
                        item.SubItems[1].Text += ps + frm.Password;
                }
                else
                    item.SubItems[1].Text += ps + frm.Password;
            }
        }

        private void saveFileBatchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFile.ShowDialog() != DialogResult.OK) return;
            var filename = saveFile.FileName;

            var list = ParserToFileDownload();
            if (list == null)
            {
                Utilites.ShowMessageError("Can not save");
                return;
            }
            ReadnWrite.Write(list, filename);
            Utilites.ShowMessage("Save Ok");
        }


        private List<FileDownload> ParserToFileDownload()
        {
            if (_filesFolderListView.Items.Count < 1) return null;
            return _filesFolderListView.Items
                .Cast<ListViewItem>()
                .Select(item => new FileDownload
                                    {
                                        Filename = item.SubItems[0].Text,
                                        QuickKey = item.SubItems[1].Text
                                            .Substring(
                                                item.SubItems[1].Text.LastIndexOf("?", StringComparison.Ordinal) +
                                                1),
                                        Size = string.IsNullOrEmpty(item.SubItems[2].Text)
                                                ? string.Empty
                                                : item.SubItems[2].Text.SizeToSize()
                                    }).ToList();

        }

        private void getAndSendToQueueStripMenuItem1_Click(object sender, EventArgs e)
        {
            foreach (var item in _filesFolderListView.SelectedItems.Cast<ListViewItem>().Where(item => item.SubItems.Count <= 3))
            {
                GetnSend2Queue(item);
                item.SubItems.Add("Sending...");
            }
        }

        private void GetnSend2Queue(ListViewItem item)
        {
            var file = new FileDownload();
            file.GetLinkDownload(item.SubItems[1].Text);
            file.PropertyChanged += (sender1, e1) =>
                                        {
                                            switch (e1.PropertyName)
                                            {
                                                case "LinkDownload":
                                                    file.LinkDownload.SendToQueue();
                                                    item.SubItems[3].Text = "Send Queue IDM";
                                                    break;
                                                case "Error":
                                                    Utilites.ShowMessageError(file.Error);
                                                    break;
                                                case "Percent":
                                                    _progressBar.Value = file.Percent;
                                                    break;
                                            }
                                        };
        }
    }
}
